//
//  AdCacheModel.swift
//  ClockWidget
//
//  Created by TSYH on 2023/11/4.
//

import Foundation

// 广告类型
public enum ADType {
    case unknow
    case launch             // 开屏
    case interstitial       // 插屏
    case reward             // 激励
    
    // 是否全屏广告
    var isFullScreenAD: Bool {
        switch self {
        case .unknow:
            return false
        case .launch, .interstitial, .reward:
            return true
        }
    }
}

public protocol ADSceneProtocol {
    // 场景广告id
    var adId: String { get }
    // 场景广告类型
    var adType: ADType { get }
}

public enum ADState {
    case willPresent
    case finished           // 关闭广告
    case fail               // 弹出失败 （包括无广告）
    case loadSuccess        // 广告加载成功
}

public typealias ADCompletionHandler = (ADState) -> Void

class ADCacheModel {
    var scene: ADSceneProtocol
    var ad: NSObject? {
        didSet {
            if ad != nil {
                loadDate = Date()
            } else {
                loadDate = nil
            }
        }
    }
    var loadDate: Date?
    var isShowing: Bool = false
    // 广告过期时间
    var adExpireInterval: TimeInterval = 4 * 3600
    var actionHandler: ADCompletionHandler?
    
    init(scene: ADSceneProtocol) {
        self.scene = scene
    }
    
    var isExpired: Bool {
        if let lastDate = loadDate {
            return Date().timeIntervalSince(lastDate) > adExpireInterval
        }
        return false
    }
    
    func clear() {
        ad = nil
        isShowing = false
    }
}
